package com.coder4j.biz.controller;

import com.coder4j.biz.entity.WechatLinkEntity;
import com.coder4j.biz.service.WechatLinkService;
import com.coder4j.biz.vo.WechatLinkQuery;
import com.coder4j.biz.vo.WechatLinkVO;
import com.coder4j.biz.vo.WechatLinkEO;
import com.coder4j.config.GlobalConfig;
import com.coder4j.log.OperationLog;
import com.coder4j.starter.tools.util.DateUtils;
import com.coder4j.starter.tools.util.FileUtils;
import com.coder4j.starter.web.api.ApiNote;
import com.coder4j.starter.mybatis.BasePage;
import com.coder4j.starter.tools.vo.R;
import com.coder4j.starter.web.jwt.AuthVO;
import com.coder4j.starter.web.util.AuthUtils;
import com.coder4j.starter.web.util.EasyExcelUtils;
import com.coder4j.starter.tools.util.ObjectUtils;
import lombok.NonNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * 微信链接分享
 * @author keller
 * @date 2024-12-12 10:43:05
 */
@Slf4j
@RestController
@RequestMapping("/wechatLink")
public class WechatLinkController {
    @Resource
    private WechatLinkService service;

    @Resource
    private HttpServletResponse response;

    //图片保存路径
    @Value("${upload.wechatImg}")
    private String savePath;

    //图片访问路径
    @Value("${nginx.wechatImg}")
    private String accessPath;

    /**
     * 按ID查询微信链接分享
     * @param id WechatLink.id
     * @return 微信链接分享对象
     */
    @GetMapping("/getById")
    @ApiNote(name="按ID查询微信链接分享",createName = "keller",createTime = "2024-12-12 10:43:05")
    public R<WechatLinkVO> getById( Long id){

        return R.success(service.baseGetVOById(id));
    }

    @GetMapping("/preview")
    @ApiNote(name="预览",createName = "keller",createTime = "2024-12-12 10:43:05")
    public R<WechatLinkEntity> review(@NonNull String link) throws Exception {
        return R.success(service.praseEntity(link));
    }
    /**
     * 保存微信链接分享
     * 有 id 字段，更新；否则新增
     * @param wechatLink WechatLink对象
     * @return WechatLink对象
     */
    @PostMapping("/save")
    @ApiNote(name="保存微信链接分享",createName = "keller",createTime = "2024-12-12 10:43:05")
    public R save(@RequestBody WechatLinkVO wechatLink){
        service.baseSaveVO(wechatLink);
        return R.success();
    }

    @PostMapping("/upload")
    @ApiNote(name="上传图片",createName = "keller",createTime = "2024-12-09 15:39:06")
    public R<String> uploadFile(@RequestParam("file") MultipartFile file) throws Exception{

        String originalFilename = file.getOriginalFilename();
        String fileName = DateUtils.getTimeMask() +  FileUtils.getSuffixName(originalFilename);

        Files.copy(file.getInputStream(),
                Paths.get(savePath + File.separator + fileName)
        );


        return R.success(accessPath + "/" + fileName);
    }


    @PostMapping("/pageForShow")
    @OperationLog("查看微信分享列表")
    @ApiNote(name="查询微信链接分享列表",createName = "keller",createTime = "2024-12-12 10:43:05")
    public R<BasePage<WechatLinkVO>> getPageForShow(@RequestBody WechatLinkQuery query){
        if(query == null){
            query = new WechatLinkQuery();
        }
        return R.success(service.baseQueryVOPage(query));
    }

    /**
     * 查询列表
     * @param query 查询条件
     * @return 数据列表
     */
    @PostMapping("/page")
    @OperationLog("查看微信分享列表")
    @ApiNote(name="查询微信链接分享列表",createName = "keller",createTime = "2024-12-12 10:43:05")
    public R<BasePage<WechatLinkVO>> getList(@RequestBody WechatLinkQuery query){
        if(query == null){
            query = new WechatLinkQuery();
        }
        AuthVO authVO = AuthUtils.getAuthVO();
        if(authVO != null && !GlobalConfig.SuperAdminRoleId.equals(authVO.getRoleId())){
            query.setCreateId(authVO.getUserId());
        }
        return R.success(service.baseQueryVOPage(query));
    }

    /**
     * 导出列表
     * @param query 查询条件
     */
    @PostMapping("/export")
    @ApiNote(name="导出微信链接分享列表",createName = "keller",createTime = "2024-12-12 10:43:05")
    public void export(@RequestBody WechatLinkQuery query){
        if(query == null){
            query = new WechatLinkQuery();
        }
        AuthVO authVO = AuthUtils.getAuthVO();
        if(authVO != null && !GlobalConfig.SuperAdminRoleId.equals(authVO.getRoleId())){
            query.setCreateId(authVO.getUserId());
        }
        List<WechatLinkEntity> list = service.baseQueryList(query);
                List<WechatLinkEO> eoList = new ArrayList<>();
                for (WechatLinkEntity entity : list) {
                    WechatLinkEO eo = new WechatLinkEO();
                    BeanUtils.copyProperties(entity,eo);
                    eoList.add(eo);
                }
                EasyExcelUtils.exportClass(response,"WechatLinkList",eoList);
    }


    /**
     * 删除微信链接分享
     * 如果Entity继承了 BaseSoftDeleteEntity，使用逻辑删除；否则，使用物理删除
     * @param id WechatLink.id
     * @return 删除的数据
     */
    @PostMapping("/deleteById")
    @ApiNote(name="删除微信链接分享",createName = "keller",createTime = "2024-12-12 10:43:05")
    public R deleteById( Long id){
        AuthVO authVO = AuthUtils.getAuthVO();
        //非超管，只能删除自己的数据
        if(!GlobalConfig.SuperAdminRoleId.equals(authVO.getRoleId())){
            WechatLinkEntity entity = service.baseGetById(id);
            if(!entity.getCreateId().equals(authVO.getUserId())){
                return R.noAuth();
            }
        }
        service.baseDeleteById(id);
        return R.success();
    }
}
